import * as echarts from '../../ec-canvas/echarts';
var util = require('../../utils/util.js');
import { Request } from "../../utils/request.js"

var request = new Request()
const app = getApp();

function initChart(canvas, width, height) {

  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
  });

  canvas.setChart(chart);

  var xAxisData = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23];
  var stData = [];
  var etData = [];
  var ptData = [];

  request.get(
    "getTodayInformation/" + app.globalData.openid + '/' + util.formatTimeTwo(new Date().getTime(), 'Y-M-D'),
    null,
    function (res) {
      console.log(res);
      if (res.statusCode != 200) {
        chart.setOption(getBarOption(xAxisData, stData, etData, ptData));
        return;
      }

      var data = res.data.result
      var xAxis = data.line.xaria
      var st = data.line.stData
      var et = data.line.etData
      var pt = []
      for (var i = 0; i <= 23; i++) {
        pt[i] = data.line.ptData[i].toFixed(2);
      }
      console.log(pt)

      chart.setOption(getBarOption(xAxis, st, et, pt));
    },
    function (res) {
      chart.setOption(getBarOption(xAxisData, stData, etData, ptData));
    }
  )

  return chart;
}

function getBarOption(xAxisData, stData, etData, ptData) {
  var title = "今日学习时长";
  var yAxisName = "分钟/(min)";


  var option = {
    color: ["#67E0E3", "#37A2DA", "#2B68D4"],
    title: {
      text: title,
      left: 'center'
    },
    legend: {
      data: ['学习时长', '有效学习时长', '效率值'],
      left: 'center',
      top: 30
    },
    grid: {
      top: 100
    },
    tooltip: {
      show: true,
      trigger: 'axis'
    },
    xAxis: {
      axisTick: {
        alignWithLabel: true
      },
      type: 'category',
      data: xAxisData,
    },
    yAxis: [{
      name: yAxisName,
      x: 'center',
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
    }, {
      name: "效率(%)",
      x: 'center',
      type: 'value',
      min: 0,
      max: 100,
      position: 'right',
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
    }],
    series: [{
      name: '学习时长',
      type: 'bar',
      data: stData
    }, {
      name: '有效学习时长',
      type: 'bar',
      data: etData
    }, {
      name: '效率值',
      type: 'line',
      yAxisIndex: 1,
      data: ptData,
      connectNulls: true
    }]
  };
  return option;
}

module.exports = {
  initBar: initChart
}